import base64
import json
from json import JSONDecodeError

from locust import task, FastHttpUser, constant, tag, run_single_user

index_cookie = 2000


def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookie.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


class MyTask(FastHttpUser):
    # wait_time = constant(1)
    host = "http://www.retone-hearing.fit:8081"
    # host = "https://192.168.10.233:8081"
    header = {"Cookie": "hearingaid_user=NmE1YWQyZmMtZGMzZC00OGU2LWI5NTgtN2IxMzNjZjRjMDQw",
              "Content-Type": "application/json"}

    # cookie = get_cookie()
    # def on_start(self):
    #     numbers_of_user = False
    #     if numbers_of_user == True:
    #         self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
    #                        "Content-Type": "application/json"}
    #     else:
    #         self.header = {"Cookie": "hearingaid_user=NmE1YWQyZmMtZGMzZC00OGU2LWI5NTgtN2IxMzNjZjRjMDQw",
    #                        "Content-Type": "application/json"}

    # @task
    # @tag('get_personal_info')
    # @tag(1)
    # def get_personal_info(self):
    #     url = '/platformRetoneFit/api/needAppUserAuth/responseEncode/requestDecode/getCurrentPersonalInfo'
    #     with self.rest('post', url, headers=self.header) as resp:
    #         try:
    #             if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['data'] != None):
    #                 resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
    #             else:
    #                 # print(resp.json())
    #                 resp.success()
    #         except JSONDecodeError:
    #             resp.failure("Response could not be decoded as JSON")
    #         except KeyError:
    #             resp.failure("Response did not contain expected key 'greeting'")

    @task
    @tag('getLoginState')
    @tag(2)
    def getLoginState(self):
        url = '/microServiceUser/responseEncode/requestDecode/getLoginState'
        with self.rest('post', url, headers=self.header) as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['data'] != None):
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    # print(resp.json())
                    resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'greeting'")

    # @task
    # @tag('userisregister')
    # @tag(3)
    # def getUserLoginObjectState(self):
    #     url = '/microServiceUser/responseEncode/requestDecode/getUserLoginObjectState'
    #     data = {
    #         "loginObject": 'tester9796',
    #         "sourcePlatform": "RETONE_FIT"
    #     }
    #     with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
    #         try:
    #             if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
    #                 resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
    #             else:
    #                 # print(resp.json())
    #                 resp.success()
    #         except JSONDecodeError:
    #             resp.failure("Response could not be decoded as JSON")
    #         except KeyError:
    #             resp.failure("Response did not contain expected key 'greeting'")


if __name__ == '__main__':
    # os.system('locust -f stress_loginstatus.py --tag get_personal_info --web-host="127.0.0.1"')
    # os.system('locust -f stress_loginstatus.py --tag getLoginState --web-host="127.0.0.1"')
    # os.system('locust -f stress_loginstatus.py --tag userisregister --web-host="127.0.0.1"')
    run_single_user(MyTask)
